package com.slt.android.windowtst;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener, View.OnTouchListener {

    Button btn , btnFloat;
    WindowManager.LayoutParams mlp;
    WindowManager windowManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(this);
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    }

    @Override
    public void onClick(View v) {
        btnFloat = new Button(this);
        btnFloat.setText("i m floating button");
        mlp = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT ,
                WindowManager.LayoutParams.WRAP_CONTENT , 0 , 0 ,
                PixelFormat.TRANSPARENT);
        mlp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;

        mlp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        mlp.gravity = Gravity.LEFT | Gravity.BOTTOM;
        mlp.x = 100;
        mlp.y = 300;
        btnFloat.setOnTouchListener(this);
        windowManager.addView(btnFloat , mlp);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int rawX = (int) event.getRawX();
        int rawY = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                break;
            }
            case MotionEvent.ACTION_MOVE: {
//                int x = (int) event.getX();
//                int y = (int) event.getY();
//                mlp.x = rawX;
//                mlp.y = rawY;
//                windowManager.updateViewLayout(btnFloat, mlp);
                break;
            }
            case MotionEvent.ACTION_UP: {
                Toast.makeText(getApplicationContext() , "我被按了" ,Toast.LENGTH_SHORT).show();
                break;
            }
            default:
                break;
        }

        return false;
    }
}
